﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;

namespace MSBTC.WinForms
{
    public partial class LostItemForm : Form
    {
        MDIParent mdipar = new MDIParent();
        PMSContext dbcontext = new PMSContext();
        Lost dblost = new Lost();
        FormHelpers help = new FormHelpers();
        private string Datamanip;
        private int rowselect;


        public LostItemForm()
        {
            InitializeComponent();
        }

        private void LostItemForm_Load(object sender, EventArgs e)
        {
            cmbChoosItem.SelectedIndex = 0;

            //retrieve all data of equipments
            var matinv = (from mi in dbcontext.MaterialsInventorys
                          select mi).ToList();
            if (matinv != null)
            {
                foreach (var mi in matinv)
                {
                    //add equipments name in combo box
                    cmbLMaterials.Items.Add(mi.Material_Name);
                }
            }
            else
            {
                MessageBox.Show("There are no equipment listed, please add equipment in Equipment Inventory in main menu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //equipment
            var equ = (from eq in dbcontext.Equipments
                       select eq).ToList();
            if (equ != null)
            {
                foreach (var eq in equ)
                {
                    //add equipments name in combo box
                    cmbLEquipments.Items.Add(eq.Equip_Name);
                }
            }
            else
            {
                MessageBox.Show("There are no equipment listed, please add equipment in Equipment Inventory in main menu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            RefreshFields();
            RefreshDB();
        }

        #region Functions
        private void RefreshDB()
        {
            //retrieve all data of projects in List
            var lost = (from eq in dbcontext.Losts
                        select eq).ToList();

            LVEquipInfo.Items.Clear();
            if (lost.Count != 0)
            {
                foreach (var sqlLost in lost)
                {
                    //add items in listview box
                    ListViewItem lvitems = LVEquipInfo.Items.Add(sqlLost.Lostid_PK.ToString());
                    //lvitems.SubItems.Add(sqlLost.Materialid_FK.ToString());

                    var mtrl = dbcontext.MaterialsInventorys.Find(sqlLost.MaterialsInventoryid_FK);
                    if (mtrl != null)
                    {
                        lvitems.SubItems.Add(mtrl.Material_Name.ToString());
                    }
                    else
                    {
                        lvitems.SubItems.Add("0");
                    }
                    var equ = dbcontext.Equipments.Find(sqlLost.Equipmentid_FK);
                    if (equ != null)
                    {
                        lvitems.SubItems.Add(equ.Equip_Name.ToString());
                    }
                    else
                    {
                        lvitems.SubItems.Add("0");
                    }
                   // lvitems.SubItems.Add(sqlLost.Description.ToString());
                    lvitems.SubItems.Add(sqlLost.QuantityCost.ToString());
                    lvitems.SubItems.Add(sqlLost.Date_Lost.ToString());
                    lvitems.SubItems.Add(sqlLost.Unit_Cost.ToString());
                    lvitems.SubItems.Add(sqlLost.Total_Cost.ToString());
                    lvitems.SubItems.Add(sqlLost.Description.ToString());

                }
            }

        }

        private void ClearFields()
        {
            txtID.Clear();
            cmbChoosItem.SelectedIndex = 0;
            cmbLMaterials.SelectedIndex = 0;
            cmbLEquipments.SelectedIndex = 0;
            txtDesc.Clear();
            txtQuantity.Clear();
            txtDateLost.Clear();
            txtUnitCost.Clear();
            txtTotCost.Clear();
            txtSearch.Clear();

        }

        private void DisableFields()
        {
            txtID.Enabled = false;
            cmbChoosItem.Enabled = false;
            cmbLMaterials.Enabled = false;
            cmbLEquipments.Enabled = false;
            txtDesc.Enabled = false;
            txtQuantity.Enabled = false;
            txtDateLost.Enabled = false;
            txtUnitCost.Enabled = false;
            txtTotCost.Enabled = false;

        }

        private void EnableFields()
        {
            txtID.Enabled = true;
            cmbChoosItem.Enabled = true;
            cmbLMaterials.Enabled = true;
            cmbLEquipments.Enabled = true;
            txtDesc.Enabled = true;
            txtQuantity.Enabled = true;
            txtDateLost.Enabled = true;
            txtUnitCost.Enabled = true;
            txtTotCost.Enabled = true;
        }

        private void RefreshFields()
        {
            DisableFields();
            ClearFields();

            btnNew.Enabled = true;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
            btnClear.Enabled = true;
            btnSave.Enabled = false;
        }
        
        private void TotCostfunc()
        {
            if (txtUnitCost.Text != "")
            {
                //var x = double.Parse(txtQuantity.Text) * double.Parse(txtUnitCost.Text);
                var x = Convert.ToDecimal(txtQuantity.Text) * Convert.ToDecimal(txtUnitCost.Text);
                txtTotCost.Text = Convert.ToString(x);
            }
        }
        
        #endregion
        
        private void cmbChoosItem_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbChoosItem.SelectedIndex == 1)
            {
                cmbLMaterials.Enabled = true;
                cmbLEquipments.Enabled = false;
                cmbLEquipments.SelectedIndex = 0;
            }
            else if (cmbChoosItem.SelectedIndex == 2)
            {
                cmbLEquipments.Enabled = true;
                cmbLMaterials.Enabled = false;
                cmbLMaterials.SelectedIndex = 0;
            }
            else
            {
                cmbLMaterials.Enabled = false;
                cmbLEquipments.Enabled = false;

            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Datamanip = "Add";

            EnableFields();
            ClearFields();

            txtTotCost.Enabled = false;
            cmbLEquipments.Enabled = false;
            cmbLMaterials.Enabled = false;
            btnSave.Enabled = true;
            btnNew.Enabled = false;
            LVEquipInfo.Enabled = false;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
          
            DialogResult YN = MessageBox.Show("Do you want to Delete it?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (YN == DialogResult.Yes)
            {
                var del = dbcontext.Losts.Find(Convert.ToInt32(txtID.Text));//get the same ID of purchase order to delete
                if (del != null)
                {
                    //delete the ID selected
                    dbcontext.Entry(del).State = EntityState.Deleted;
                    dbcontext.SaveChanges();
                }
                RefreshFields();
                RefreshDB();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Datamanip = "Edit";

            EnableFields();

            txtTotCost.Enabled = false;
            cmbLEquipments.Enabled = false;
            cmbLMaterials.Enabled = false;
            btnSave.Enabled = true;
            btnNew.Enabled = false;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
        }

        private void LVEquipInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //focus the selected items
            rowselect = LVEquipInfo.FocusedItem.Index;

            //getting the information from the listview to textbox
            txtID.Text = LVEquipInfo.Items[rowselect].SubItems[0].Text;
            cmbLMaterials.SelectedItem = LVEquipInfo.Items[rowselect].SubItems[1].Text;
            cmbLEquipments.SelectedItem = LVEquipInfo.Items[rowselect].SubItems[2].Text;
            txtDesc.Text = LVEquipInfo.Items[rowselect].SubItems[7].Text;
            txtQuantity.Text = LVEquipInfo.Items[rowselect].SubItems[5].Text;
            txtDateLost.Text = LVEquipInfo.Items[rowselect].SubItems[4].Text;
            txtUnitCost.Text = LVEquipInfo.Items[rowselect].SubItems[3].Text;
            txtTotCost.Text = LVEquipInfo.Items[rowselect].SubItems[6].Text;




            btnDel.Enabled = true;
            btnEdit.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((txtDesc.Text == null) || (txtQuantity.Text == null) || (txtDateLost.Text == null) || (txtUnitCost.Text == null) || (txtTotCost.Text == null))
            {
                MessageBox.Show("Please fill up the missing fields", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if ((cmbLMaterials.SelectedIndex == 0) || (cmbLEquipments.SelectedIndex == 0))
            {
                MessageBox.Show("Please Select materials or equipment", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                if (Datamanip == "Add")
                {
                    if (cmbChoosItem.SelectedIndex == 1)
                    {
                        

                        var matinv = (from m in dbcontext.MaterialsInventorys
                                      where m.Material_Name == cmbLMaterials.SelectedItem
                                      select m).SingleOrDefault();


                        var los = (from lo in dbcontext.Losts
                                   where lo.MaterialsInventoryid_FK == matinv.MaterialsInventoryid_PK /*&& lo.Equipid_FK == equ.Equipmentid_PK*/
                                   select lo).SingleOrDefault();

                        if (los == null)
                        {
                            dblost.MaterialsInventoryid_FK = matinv.MaterialsInventoryid_PK;
                            dblost.Equipmentid_FK = 0;
                            dblost.Description = txtDesc.Text;
                            dblost.QuantityCost = Convert.ToDecimal(txtQuantity.Text);
                            dblost.Date_Lost = txtDateLost.Text;
                            dblost.Unit_Cost = Convert.ToDecimal(txtUnitCost.Text);
                            dblost.Total_Cost = Convert.ToDecimal(txtTotCost.Text);


                            dbcontext.Entry(dblost).State = EntityState.Added;
                            dbcontext.SaveChanges();

                            MessageBox.Show("Successfully Saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshFields();
                            RefreshDB();
                        }
                        else
                        {
                            DialogResult YN = MessageBox.Show("Materials already exist in lost record, do you want to update records with the one you've inputted?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (YN == DialogResult.Yes)
                            {

                                var rep = dbcontext.Losts.Find(los.Lostid_PK);

                                rep.QuantityCost += Convert.ToInt32(txtQuantity.Text);
                                rep.Description = txtDesc.Text;
                                rep.Total_Cost += Convert.ToDecimal(txtTotCost.Text);
                                rep.Unit_Cost = Convert.ToDecimal(txtUnitCost.Text);
                                rep.Date_Lost = txtDateLost.Text;

                                MessageBox.Show("Success");

                            }
                        }

                    }

                    else if (cmbChoosItem.SelectedIndex == 2)
                    {
                        var equ = (from eq in dbcontext.Equipments
                                   where eq.Equip_Name == cmbLEquipments.SelectedItem
                                   select eq).SingleOrDefault();


                        var los = (from lo in dbcontext.Losts
                                   where lo.Equipmentid_FK == equ.Equipmentid_PK
                                   select lo).SingleOrDefault();

                        if (los == null)
                        {
                            dblost.MaterialsInventoryid_FK = 0;
                            dblost.Equipmentid_FK = equ.Equipmentid_PK;
                            dblost.Description = txtDesc.Text;
                            dblost.QuantityCost = Convert.ToDecimal(txtQuantity.Text);
                            dblost.Date_Lost = txtDateLost.Text;
                            dblost.Unit_Cost = Convert.ToDecimal(txtUnitCost.Text);
                            dblost.Total_Cost = Convert.ToDecimal(txtTotCost.Text);


                            dbcontext.Entry(dblost).State = EntityState.Added;
                            dbcontext.SaveChanges();

                            MessageBox.Show("Successfully Saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshFields();
                            RefreshDB();
                        }

                        else
                        {
                            DialogResult YN = MessageBox.Show("Materials already exist in lost record, do you want to update records with the one you've inputted?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (YN == DialogResult.Yes)
                            {

                                var rep = dbcontext.Losts.Find(los.Lostid_PK);

                                rep.QuantityCost += Convert.ToInt32(txtQuantity.Text);
                                rep.Description = txtDesc.Text;
                                rep.Total_Cost += Convert.ToDecimal(txtTotCost.Text);
                                rep.Unit_Cost = Convert.ToDecimal(txtUnitCost.Text);
                                rep.Date_Lost = txtDateLost.Text;

                                MessageBox.Show("Success");

                            }
                        }
                    }


                    else
                    {
                        MessageBox.Show("Please choose item.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    RefreshDB();
                    RefreshFields();
                    LVEquipInfo.Enabled = true;
                }
                else if (Datamanip == "Edit")
                {
                    DialogResult YN = MessageBox.Show("Do you want to apply changes?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (YN == DialogResult.Yes)
                    {
                        var replaceMat = dbcontext.MaterialsInventorys.Find(Convert.ToInt32(txtID.Text));
                        var replaceEqu = dbcontext.Equipments.Find(Convert.ToInt32(txtID.Text));
                        var replace = dbcontext.Losts.Find(Convert.ToInt32(txtID.Text));

                       
                        replaceMat.Material_Name = cmbLMaterials.Text;
                        replaceEqu.Equip_Name = cmbLEquipments.Text;
                        replace.Description = txtDesc.Text;
                        replace.QuantityCost = Convert.ToInt32(txtQuantity.Text);
                        replace.Date_Lost = txtDateLost.Text;
                        replace.Unit_Cost = Convert.ToInt32(txtUnitCost.Text);
                        replace.Total_Cost = Convert.ToInt32(txtTotCost.Text);

                        dbcontext.Entry(replace).State = EntityState.Modified;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Modified.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                    }
                }
                }
            }
        

        private void txtUnitCost_TextChanged(object sender, EventArgs e)
        {
            TotCostfunc();
        }

        private void cmbLMaterials_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbChoosItem.Enabled = false;
        }

        private void cmbLEquipments_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbChoosItem.Enabled = false;
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                RefreshDB();
            }
            else
            {
                LVEquipInfo.Items.Clear();
                var eq = (from p in dbcontext.Equipments
                          where p.Equip_Name.Contains(txtSearch.Text)
                          select p).ToList();
                if (eq.Count != 0)
                {
                    foreach(var itm in eq)
                    {
                        var lost = (from l in dbcontext.Losts
                                    where l.Equipmentid_FK == itm.Equipmentid_PK
                                    select l).SingleOrDefault();
                        if (lost != null)
                        {
                            ListViewItem lvitems = LVEquipInfo.Items.Add(lost.Lostid_PK.ToString());
                            lvitems.SubItems.Add("");
                            lvitems.SubItems.Add(itm.Equip_Name.ToString());
                            lvitems.SubItems.Add(itm.Quantity.ToString());
                            lvitems.SubItems.Add(lost.Date_Lost.ToString());
                            lvitems.SubItems.Add(lost.Total_Cost.ToString());
                            lvitems.SubItems.Add(lost.Description.ToString());
                        }
                    }
                }
                //else
                //{
                    var mat = (from m in dbcontext.MaterialsInventorys
                               where m.Material_Name.Contains(txtSearch.Text)
                               select m).ToList();
                    if (mat.Count != 0)
                    {
                        foreach (var itm in mat)
                        {
                            var lost = (from l in dbcontext.Losts
                                        where l.MaterialsInventoryid_FK == itm.MaterialsInventoryid_PK
                                        select l).SingleOrDefault();
                            if (lost != null)
                            {
                                ListViewItem lvitems = LVEquipInfo.Items.Add(lost.Lostid_PK.ToString());
                                lvitems.SubItems.Add(itm.Material_Name.ToString());
                                lvitems.SubItems.Add("");
                                lvitems.SubItems.Add(itm.Qty.ToString());
                                lvitems.SubItems.Add(lost.Date_Lost.ToString());
                                lvitems.SubItems.Add(lost.Total_Cost.ToString());
                                lvitems.SubItems.Add(lost.Description.ToString());
                            }
                        }
                    }
                 //}

            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            RefreshFields();
            LVEquipInfo.Enabled = true;
        }

    }


}







